Imports System.Net
Imports System.IO
Imports System.Text

Friend Class PoserProsDownloader
    Inherits BaseDownloader

    Friend Const BASE_PAGE_URL As String = "http://poserpros.daz3d.com/store/viewitem.php?selitem={0}"
    Private Const IMAGE_URL As String = "http://poserpros.daz3d.com/store/images/products/{0}_00.jpg"

    Private Const READ_ME_URL As String = "http://poserpros.daz3d.com/store/viewreadme.php?selitem={0}"

    Private Const URL_TO_REMOVE As String = "http://poserpros.daz3d.com/store/viewitem.php?selitem="

    Private Const FIRST_ANCHOR_MATCH As String = "<form target=""wishlist"" action=""wishlist.php"" method=""post"">"
    Private Const SECOND_ANCHOR_MATCH As String = "<td width=""480"" align=""center"">"

    Private Const PRODUCT_IMAGE_START_MATCH As String = "<img src=""images/products/"
    Private Const PRODUCT_IMAGE_END_MATCH As String = """ border=""0"" align=""right"" hspace=""8"" vspace=""8"">"

    Private Const PRICE_START_MATCH As String = "<tr><td align=left><span class=""genbig"">by <a href="""
    Private Const PRICE_START_END_MATCH As String = "</a><br/>$"
    Private Const PRICE_START_END_MATCH_2 As String = "</a><br/>Reg: $"
    Private Const PRICE_END_MATCH As String = "/ &euro;"

    Private Const STRIKE_START As String = "<strike>"
    Private Const STRIKE_END As String = "</strike>"

    Private Const PRODUCT_NAME_START_MATCH As String = "<span class=""maintitle"">"
    Private Const PRODUCT_NAME_END_MATCH As String = "</span>"

    Private Const ARTIST_START_MATCH As String = "<tr><td align=left><span class=""genbig"">by <a href="""
    Private Const ARTISTS_START_END_MATCH As String = """ >"
    Private Const ARTIST_END_MATCH As String = "</a><br/>"

    Private Const REQUIREMENTS_START_MATCH As String = "<br /><b>Required Products:</b>"
    Private Const REQUIREMENTS_START_END_MATCH As String = "<br /><li>"
    Private Const REQUIREMENTS_END_MATCH As String = "<br /></span>"

    Public Const LINK_FILENAME As String = "PoserProsLinks.xml"

    Friend Const CODE_BASE As String = "PP"

    Public Overrides ReadOnly Property BasePageUrl() As String
        Get
            Return BASE_PAGE_URL
        End Get
    End Property

    Public Overrides ReadOnly Property BaseImageUrl() As String
        Get
            Return IMAGE_URL
        End Get
    End Property

    Public Overrides ReadOnly Property LinkFilename() As String
        Get
            Return LINK_FILENAME
        End Get
    End Property

    Public Overrides ReadOnly Property UrlToRemove() As String
        Get
            Return URL_TO_REMOVE
        End Get
    End Property

    Public Sub New(ByVal imageDirectory As String, _
                   ByVal imageHolder As PictureBox)
        MyBase.New(imageDirectory, _
                    imageHolder)
    End Sub

    Public Overrides Function DownloadImage(ByVal productCode As String, _
                                            ByVal productUrl As String) As String

        Dim productId As Integer = 0

        Try
            productId = CType(productUrl.Replace(URL_TO_REMOVE, EMPTY), Integer)
        Catch ex As Exception
            Throw New InvalidProductUrlException
        End Try

        DownloadImage(productId, _
                      productCode)

        Return CODE_BASE & productId & JPEG_EXTENSION

    End Function

    Protected Overrides Sub DownLoadImage(ByVal imageId As Integer, _
                                            ByVal productCode As String)


        Try
            Dim fileName As String = My.Settings.ImageDirectory
            fileName &= CODE_BASE
            fileName &= imageId.ToString
            fileName &= JPEG_EXTENSION

            Dim imageName As String = imageId.ToString
            Select Case imageId
                Case Is < 100
                    imageName = "0000" & imageName
                Case Is < 1000
                    imageName = "000" & imageName
                Case Is < 10000
                    imageName = "00" & imageName
            End Select

            _imageHolder.Load(String.Format(BaseImageUrl, imageName))
            _imageHolder.Image.Save(fileName, _
                                    System.Drawing.Imaging.ImageFormat.Jpeg)
            Application.DoEvents()
        Catch ex As System.Net.WebException
            If ex.Status <> WebExceptionStatus.ProtocolError Then
                MsgBox(ex.Message)
            End If
        Catch ex As Exception
            MsgBox(ex.Message)
        Finally

        End Try

    End Sub

    Public Shared Function GetReadMe(ByVal productCode As String) As String

        Dim readMeText As String = ""

        Try

            productCode = productCode.Replace(CODE_BASE, EMPTY)

        Catch ex As Exception
            Throw New InvalidProductUrlException
        End Try

        Dim request As HttpWebRequest = CType(WebRequest.Create(String.Format(READ_ME_URL, productCode)), _
                                                  HttpWebRequest)
        request.KeepAlive = False

        Dim response As HttpWebResponse = CType(request.GetResponse(), _
                                                HttpWebResponse)

        Dim receiveStream As Stream = response.GetResponseStream()
        Dim readStream As New StreamReader(receiveStream, _
                                           Encoding.UTF8)

        Dim pageContents As String = readStream.ReadToEnd

        readStream.Close()
        response.Close()

        Return pageContents

    End Function


    Private Function GetProductName(ByVal pageContents As String) As String

        Dim productCodeStart As Integer = pageContents.IndexOf(PRODUCT_NAME_START_MATCH)
        Dim productName As String = ""

        If productCodeStart > -1 Then
            pageContents = pageContents.Substring(productCodeStart)
            pageContents = pageContents.Substring(0, pageContents.IndexOf(PRODUCT_NAME_END_MATCH))
            pageContents = pageContents.Replace(PRODUCT_NAME_START_MATCH, EMPTY)
            productName = pageContents.Trim
        End If

        Return productName

    End Function

    Private Function GetPrice(ByVal pageContents As String) As Single

        Dim productCodeStart As Integer = pageContents.IndexOf(PRICE_START_MATCH)
        Dim price As Single = 0.0

        If productCodeStart > -1 Then
            pageContents = pageContents.Substring(productCodeStart)
            If pageContents.IndexOf(PRICE_START_END_MATCH_2) > -1 Then
                pageContents = pageContents.Substring(pageContents.IndexOf(PRICE_START_END_MATCH_2))
                pageContents = pageContents.Substring(0, pageContents.IndexOf(PRICE_END_MATCH))
                pageContents = pageContents.Replace(PRICE_START_END_MATCH_2, EMPTY)
            Else
                pageContents = pageContents.Substring(pageContents.IndexOf(PRICE_START_END_MATCH))
                pageContents = pageContents.Substring(0, pageContents.IndexOf(PRICE_END_MATCH))
                pageContents = pageContents.Replace(PRICE_START_END_MATCH, EMPTY)
            End If
            Try
                price = CType(pageContents, Single)
            Catch ex As Exception
                MsgBox(ex.Message)
            End Try

        End If

            Return price

    End Function

    Private Function GetRequiredProducts(ByVal pageContents As String) As String

        Dim requiredProducts As String = ""
        Dim requiredProductTemp As String = ""

        Dim requiredProductsStart As Integer = pageContents.IndexOf(REQUIREMENTS_START_MATCH)

        'If requiredProductsStart > -1 Then
        '    pageContents = pageContents.Substring(requiredProductsStart)
        '    pageContents = pageContents.Substring(0, pageContents.IndexOf(REQUIRED_PRODUCT_END_MATCH))
        '    pageContents = pageContents.Replace(REQUIRED_PRODUCT_START_MATCH, EMPTY)
        '    requiredProductsStart = pageContents.IndexOf(REQUIRED_PRODUCT_SEPERATOR_START_END)
        '    While requiredProductsStart > -1
        '        requiredProductTemp = pageContents.Substring(requiredProductsStart)
        '        requiredProductTemp = requiredProductTemp.Substring(0, requiredProductTemp.IndexOf(REQUIRED_PRODUCT_SEPERATOR_END))
        '        requiredProductTemp = requiredProductTemp.Replace(REQUIRED_PRODUCT_SEPERATOR_START_END, EMPTY)
        '        If requiredProducts.Length > 0 Then
        '            requiredProducts &= REQUIRED_PRODUCT_SEPERATOR
        '        End If
        '        requiredProducts &= requiredProductTemp
        '        pageContents = pageContents.Substring(pageContents.IndexOf(REQUIRED_PRODUCT_SEPERATOR_END) + REQUIRED_PRODUCT_SEPERATOR_END.Length)
        '        requiredProductsStart = pageContents.IndexOf(REQUIRED_PRODUCT_SEPERATOR_START_END)
        '    End While
        'End If

        Return requiredProducts

    End Function

    Protected Overrides Sub DownLoadPage(ByVal itemId As Integer)

        Try
            Dim pageContents As String = GetPageContents(itemId)
            Dim requiredProducts As String = ""
            Dim productName As String = ""
            Dim price As Single = 0.0

            Dim productCodeStart As Integer = pageContents.IndexOf(PRODUCT_IMAGE_START_MATCH)

            If productCodeStart > -1 Then
                requiredProducts = GetRequiredProducts(pageContents)
                price = GetPrice(pageContents)
                productName = GetProductName(pageContents)

                pageContents = pageContents.Substring(productCodeStart)
                pageContents = pageContents.Substring(0, pageContents.IndexOf(PRODUCT_IMAGE_END_MATCH))
                pageContents = pageContents.Replace(PRODUCT_IMAGE_START_MATCH, EMPTY)

                _linkFile.AddLink(itemId.ToString, _
                              String.Format(BASE_PAGE_URL, itemId.ToString), _
                              itemId, _
                              requiredProducts, _
                              productName, _
                              price)


            End If
        Catch ex As WebException
            If ex.Message <> PageNotFoundMessage Then
                Throw
            End If
            MsgBox(ex.Message)
        End Try

    End Sub


    Public Overrides Sub Download()


        Try

            Dim MinPoserProsId As Integer = _linkFile.MaxId + 1

            Download(MinPoserProsId, _
                     My.Settings.MaxPoserProsId)

        Catch ex As Exception
            MsgBox(ex.Message)
        End Try
        _linkFile.WriteFile(LINK_FILENAME)

    End Sub

End Class
